package com.zhilei.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 异步删除本地文件
 *
 * @author 志磊
 * @serial 2024-09-20
 */
@Component
public class AsyncFileService {

    @Async
    public void deleteLocalFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
                System.out.println("临时文件已删除: " + filePath);
            }
        } catch (Exception e) {
            System.err.println("删除临时文件失败: " + filePath);
            e.printStackTrace();
        }
    }

    @Async
    public void deleteFileAsync(String filePath) {
        deleteDirectory(new File(filePath).getParentFile());
        System.out.println("临时文件已删除: " + filePath);
    }

    private void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file); // 递归删除子文件夹
                    } else {
                        file.delete(); // 删除文件
                    }
                }
            }
            directory.delete(); // 删除空文件夹
        }
    }
}
